﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using Runda.CMS.Bll;
using System.Data;
using Runda.CMS.Common.Utility;

namespace Runda.CMS.Portal.Budget
{
    public partial class SalesBudgetList : BasePage
    {
        public string SortString
        {
            get
            {
                if (ViewState["SortString"] == null)
                {
                    ViewState["SortString"] = "customername";
                }

                return ViewState["SortString"].ToString();
            }
            set { ViewState["SortString"] = value; }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                for (int i = 2012; i <= 2015; i++)
                {
                    ddlBudgetYear.Items.Add(new ListItem(i.ToString(), i.ToString()));
                }

                DataTable dt = new BudgetBll().Companylist(base.CurrentUserID.ToString());
                ddlCompany.DataSource = dt;
                ddlCompany.DataTextField = "Departmentname";
                ddlCompany.DataValueField = "DepartmentCode";
                ddlCompany.DataBind();
                ddlCompany.Items.Add(new ListItem("--不限--", "0"));
                ddlCompany.SelectedValue = "0";

                dt = new BudgetBll().Departmentlist(base.CurrentUserID.ToString());
                ddlDept.DataSource = dt;
                ddlDept.DataTextField = "Departmentname";
                ddlDept.DataValueField = "Departmentname";
                ddlDept.DataBind();
                ddlDept.Items.Add(new ListItem("--不限--", "0"));
                ddlDept.SelectedValue = "0";

                ddlBudgetYear.SelectedValue = "2013";
                BindGrid(1);
                Calculate();

                if (!base.CheckUserHasFuction(1, "Func10011"))
                {
                    lnkbtnSubmit.Visible = false;
                    spanAddDuty.Visible = false;
                }
                else
                {
                    //已提交后，无法新增和再次提交
                    if (new BudgetBll().GetBudgetSubmitStatus(ddlBudgetYear.SelectedValue.ToString(), base.CurrentUserEntity.UserName) > 0)
                    { lnkbtnSubmit.Visible = false; spanAddDuty.Visible = false; }
                }
                

            }
        }
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            BindGrid(AspNetPager1.CurrentPageIndex);
            Calculate();
        }

        protected void gridAccessoryList_ItemCommand(object source, Telerik.WebControls.GridCommandEventArgs e)
        {
            if (e.CommandName.ToLower() == "delete")
            {
                
                BudgetBll bll = new BudgetBll();
                
                //BGSalesBudgetsEntity entity = bll.Get<BGSalesBudgetsEntity>(new Guid(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["BudgetID"].ToString()));
                //if (new BudgetBll().GetBudgetSubmitStatus(ddlBudgetYear.SelectedValue.ToString(), Product) == 0)
                bll.DeleteByBudgetID(new Guid(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["BudgetID"].ToString()));
               
            }
            BindGrid(AspNetPager1.CurrentPageIndex);
            Calculate();
        }

        protected void gridAccessoryList_ItemDataBound(object sender, Telerik.WebControls.GridItemEventArgs e)
        {
            if (e.Item.ItemType == Telerik.WebControls.GridItemType.Item || e.Item.ItemType == Telerik.WebControls.GridItemType.AlternatingItem)
            {
                HyperLink lnkEdit = e.Item.FindControl("lnkEdit") as HyperLink;
                LinkButton lnkbtnDelete = e.Item.FindControl("lnkbtnDelete") as LinkButton;
                if (lnkEdit != null && lnkbtnDelete != null)
                {
                    DataRowView dv = e.Item.DataItem as DataRowView;
                    if (new BudgetBll().GetBudgetSubmitStatus(ddlBudgetYear.SelectedValue.ToString(), dv["ProductManager"].ToString()) > 0 || !base.CheckUserHasFuction(1, "Func10011"))
                    { lnkbtnDelete.Visible = false; }
                    
                    lnkEdit.NavigateUrl = "~/Budget/SalesbudgetDetail.aspx?AssistID=" + dv["AssistID"].ToString();
                    lnkbtnDelete.OnClientClick = "return OnDelConfirm();";
                }
            }
        }

        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            BindGrid(AspNetPager1.CurrentPageIndex);
            Calculate();
        }

        protected void btnRefersh_Click(object sender, EventArgs e)
        {
            BindGrid(AspNetPager1.CurrentPageIndex);
            Calculate();
        } 

        private void BindGrid(int pageindex)
        {
            string sb = getWhereClause();

            int RecordCount = 0;
            DataTable dt = new BudgetBll().QuerySalesBudgets(sb, SortString, AspNetPager1.PageSize, pageindex, out RecordCount);

            AspNetPager1.RecordCount = RecordCount;
            gridAccessoryList.DataSource = dt;
            gridAccessoryList.DataBind();
        }

        private void Calculate()
        {
            string sb = getWhereClause();

            BudgetBll bll = new BudgetBll();
            DataTable dt = bll.CalcSalesBudgets(sb);

            if (dt != null && dt.Rows.Count > 0)
            {
                hfsumQ1quantity.Value = string.Format("{0:N}", dt.Rows[0]["sumQ1quantity"]);
                hfsumQ1Amount.Value = string.Format("{0:N}", dt.Rows[0]["sumQ1Amount"]);
                hfsumQ1Cost.Value = string.Format("{0:N}", dt.Rows[0]["sumQ1Cost"]);
                hfsumQ1RentAmount.Value = string.Format("{0:N}", dt.Rows[0]["sumQ1RentAmount"]);

                hfsumQ2quantity.Value = string.Format("{0:N}", dt.Rows[0]["sumQ2quantity"]);
                hfsumQ2Amount.Value = string.Format("{0:N}", dt.Rows[0]["sumQ2Amount"]);
                hfsumQ2Cost.Value = string.Format("{0:N}", dt.Rows[0]["sumQ2Cost"]);
                hfsumQ2RentAmount.Value = string.Format("{0:N}", dt.Rows[0]["sumQ2RentAmount"]);

                hfsumQ3quantity.Value = string.Format("{0:N}", dt.Rows[0]["sumQ3quantity"]);
                hfsumQ3Amount.Value = string.Format("{0:N}", dt.Rows[0]["sumQ3Amount"]);
                hfsumQ3Cost.Value = string.Format("{0:N}", dt.Rows[0]["sumQ3Cost"]);
                hfsumQ3RentAmount.Value = string.Format("{0:N}", dt.Rows[0]["sumQ3RentAmount"]);

                hfsumQ4quantity.Value = string.Format("{0:N}", dt.Rows[0]["sumQ4quantity"]);
                hfsumQ4Amount.Value = string.Format("{0:N}", dt.Rows[0]["sumQ4Amount"]);
                hfsumQ4Cost.Value = string.Format("{0:N}", dt.Rows[0]["sumQ4Cost"]);
                hfsumQ4RentAmount.Value = string.Format("{0:N}", dt.Rows[0]["sumQ4RentAmount"]);
                hfsumTotalAmount.Value = string.Format("{0:N}", dt.Rows[0]["TotalAmount"]);
                hfsumTotalRentAmount.Value = string.Format("{0:N}", dt.Rows[0]["TotalRentAmount"]);

            }
            else
            {
                hfsumQ1quantity.Value = "0";
                hfsumQ1Amount.Value = "0";
                hfsumQ1Cost.Value = "0";
                hfsumQ1RentAmount.Value = "0";

                hfsumQ2quantity.Value = "0";
                hfsumQ2Amount.Value = "0";
                hfsumQ2Cost.Value = "0";
                hfsumQ2RentAmount.Value = "0";

                hfsumQ3quantity.Value = "0";
                hfsumQ3Amount.Value = "0";
                hfsumQ3Cost.Value = "0";
                hfsumQ3RentAmount.Value = "0";

                hfsumQ4quantity.Value = "0";
                hfsumQ4Amount.Value = "0";
                hfsumQ4Cost.Value = "0";
                hfsumQ4RentAmount.Value = "0";
                hfsumTotalAmount.Value = "0";

            }
        }

        protected void gridAccessoryList_SortCommand(object source, Telerik.WebControls.GridSortCommandEventArgs e)
        {
            string OrderBy = e.SortExpression + " " + (e.NewSortOrder == Telerik.WebControls.GridSortOrder.Ascending ? "asc" : "desc");
            SortString = OrderBy;
            BindGrid(1);
            Calculate();
            

        }
        private string getWhereClause()
        { 
            StringBuilder sb = new StringBuilder();

            if (ddlBudgetYear.SelectedValue != string.Empty)
            {
                sb.Append(" and [BudgetYear]  = '").Append(ddlBudgetYear.SelectedValue).Append("'");
            }

            if (this.txtCustomerName.Text.Trim() != "")
            {
                sb.Append(" and [CustomerName]  like '%").Append(txtCustomerName.Text.Trim()).Append("%'");
            }

            int RecordCount = 0;
            RecordCount = new BudgetBll().getDataright(base.CurrentUserID.ToString());

            //if (RecordCount == 0)
            //{ sb.Append(" and ([productmanager] ='").Append(base.CurrentUserEntity.UserName).Append("'").Append(" or [biller] ='").Append(base.CurrentUserID.ToString()).Append("')"); }
            //else
            //{ sb.Append(" and [productmanager] in(").Append("select username from vw_sysUser where DepartmentID in(select DepartmentID from Cms_Sys_UserDepartment_DataRight where userid ='").Append(base.CurrentUserID.ToString()).Append("'))"); }

            sb.Append(" and (company in(").Append("select DepartmentCode from cms_sys_Department where iscompany = 1 and DepartmentID in(select DepartmentID from Cms_Sys_UserDepartment_DataRight where userid ='").Append(base.CurrentUserID.ToString()).Append("'))");
            sb.Append(" and left(productCategoryCode,6) in(").Append("select categoryCode from Cms_Ctrt_InstrumentCategory where categoryGUID in(select categoryGUID from Cms_sys_UserProductCategory where UserID ='").Append(base.CurrentUserID.ToString()).Append("')))");
                

            if (ddlCompany.SelectedValue != "0")
            {
                sb.Append(" and company='").Append(ddlCompany.SelectedValue.ToString()).Append("'");
            }
            if (ddlDept.SelectedValue != "0")
            { sb.Append(" and [productmanager] in(").Append("select username from vw_sysUser where DepartmentName ='").Append(ddlDept.SelectedValue.ToString()).Append("')"); }


            if (txtCustomerName.Text.Trim() != "")
            {
                sb.Append(" and customerID in(").Append("select customerid from cms_ctrt_customer where customername like '%").Append(txtCustomerName.Text.Trim()).Append("%')");
            }
            if (txtSalesAgencyName.Text.Trim() != "")
            {
                sb.Append(" and SalesAgencyID in(").Append("select customerid from cms_ctrt_customer where customername like '%").Append(txtSalesAgencyName.Text.Trim()).Append("%')");
            }
            if (txtCategoryName.Text.Trim() != "")
            {
                sb.Append(" and ProductCategoryID in(").Append("select  categoryGUID from Cms_Ctrt_InstrumentCategory where categoryName like '%").Append(txtCategoryName.Text.Trim()).Append("%')");
            }
            if (txtSales.Text.Trim() != "")
            {
                sb.Append(" and sales = '").Append(txtSales.Text.Trim()).Append("'");
            }


            return sb.ToString();
        }

        protected void btnExportExcel_Click(object sender, EventArgs e)
        {
            string Whereclause = getWhereClause();

            BudgetBll bll = new BudgetBll();

            DataTable dt = bll.ExportSalesBudgets(Whereclause, " [客户] asc ");

            Export.Export2Excel(dt, "销售预算一览表", Page.Response);

        }

        protected void lnkbtnSubmit_Click(object sender, EventArgs e)
        {

            BudgetBll bll = new BudgetBll();
            bll.SubmmitBudget(ddlBudgetYear.SelectedValue.ToString(), base.CurrentUserEntity.UserName);
            lnkbtnSubmit.Enabled = false;

        }

        protected void lnkbtnCheck_Click(object sender, EventArgs e)
        {

            BudgetBll bll = new BudgetBll();
            //bll.CheckBudget(ddlBudgetYear.SelectedValue.ToString(), base.CurrentUserEntity.UserName);
        }

        protected void ddlBudgetYear_SelectedIndexChanged(object sender, EventArgs e)
        {
            lnkbtnSubmit.Visible = true; spanAddDuty.Visible = true;
            //已提交后，无法新增和再次提交
            if (new BudgetBll().GetBudgetSubmitStatus(ddlBudgetYear.SelectedValue.ToString(), base.CurrentUserEntity.UserName) > 0)
            { lnkbtnSubmit.Visible = false; spanAddDuty.Visible = false; }
        }
    }
}
